#include "Common.h"
#include "MeshManager.h"
#include "Mesh.h"
#include "ShapeHelper.h"
#include "BoxShape.h"
#include "MeshSerializer.h"


MeshManager::MeshManager()
{
}

MeshManager::~MeshManager()
{
	RemoveAll();
}

Mesh* MeshManager::Create(const std::string& name)
{
	if (GetByName(name) != NULL)
		return NULL;

	Mesh* mesh = new Mesh(name);
	mMeshs[name] = mesh;

	return mesh;
}

Mesh* MeshManager::Load(const std::string& name)
{
	Mesh* ret = GetByName(name);
	if (ret != NULL)
		return ret;

	ret = Create(name);

	MeshSerializer ser;
	if (!ser.ImportMesh(name, ret))
	{
		RemoveByName(name);
		return NULL;
	}

	return ret;
}

Mesh* MeshManager::GetByName(const std::string& name)
{
	MeshMap::iterator it = mMeshs.find(name);
	if (it != mMeshs.end())
		return it->second;
	return NULL;
}

bool MeshManager::RemoveByName(const std::string& name)
{
	MeshMap::iterator it = mMeshs.find(name);
	if (it == mMeshs.end())
		return false;

	delete it->second;
	mMeshs.erase(it);
	return true;
}

void MeshManager::RemoveAll()
{
	for (MeshMap::iterator it(mMeshs.begin()), end(mMeshs.end()); it != end; it++)
		delete it->second;
	mMeshs.clear();
}

void MeshManager::BuildShapeMeshes()
{
	ShapeHelper::BuildBox(BoxShape::SHAPE_MESH_NAME, 100.0f, 100.0f, 100.0f);
}

